#include "chatwindow.h"
#include "chatmessagewidget.h"

// 首先包含Qt网络和SSL头文件
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QSslConfiguration>
#include <QSslSocket>

// 然后包含其他Qt头文件
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QScrollArea>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QScrollBar>
#include <QSettings>
#include <QMenuBar>
#include <QStatusBar>
#include <QAction>
#include <QInputDialog>
#include <QTimer>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QMenu>
#include <QDebug>

ChatWindow::ChatWindow(QWidget *parent) : QMainWindow(parent)
{
    m_apiKey = "sk-18346c6b81644d67adbb94d0e58a0935";

    // 简化SSL检查，避免使用不完整的类型
    qDebug() << "SSL support:" << QSslSocket::supportsSsl();

    setupUI();
    setupNetworking();
    loadSettings();
}

// 移除有问题的SSL密码套件检查代码
void ChatWindow::setupNetworking()
{
    m_networkManager = new QNetworkAccessManager(this);

    // 简化SSL错误处理
    connect(m_networkManager, &QNetworkAccessManager::sslErrors,
            this, [](QNetworkReply *reply, const QList<QSslError> &errors) {
        qWarning() << "Ignoring SSL errors:";
        for (const auto &error : errors) {
            qWarning() << " -" << error.errorString();
        }
        reply->ignoreSslErrors();
    });

    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &ChatWindow::onApiReplyFinished);
}

ChatWindow::~ChatWindow()
{
    saveSettings();
}

void ChatWindow::setupUI()
{
    m_centralWidget = new QWidget(this);
    m_mainLayout = new QVBoxLayout(m_centralWidget);
    m_mainLayout->setSpacing(10);
    m_mainLayout->setContentsMargins(15, 15, 15, 15);

    // 标题
    QLabel *titleLabel = new QLabel("DeepSeek AI Chat");
    titleLabel->setStyleSheet("QLabel {"
                             "font-size: 18px;"
                             "font-weight: bold;"
                             "color: #2c3e50;"
                             "padding: 10px;"
                             "}");
    titleLabel->setAlignment(Qt::AlignCenter);
    m_mainLayout->addWidget(titleLabel);

    // 聊天区域
    m_scrollArea = new QScrollArea();
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_scrollArea->setStyleSheet("QScrollArea {"
                               "background-color: white;"
                               "border: 2px solid #e9ecef;"
                               "border-radius: 8px;"
                               "}");

    m_messagesWidget = new QWidget();
    m_messagesLayout = new QVBoxLayout(m_messagesWidget);
    m_messagesLayout->setAlignment(Qt::AlignTop);
    m_messagesLayout->setSpacing(15);
    m_messagesLayout->setContentsMargins(15, 15, 15, 15);

    m_scrollArea->setWidget(m_messagesWidget);
    m_mainLayout->addWidget(m_scrollArea, 1);

    // 输入区域
    m_inputLayout = new QHBoxLayout();

    m_inputField = new QLineEdit();
    m_inputField->setPlaceholderText("Type your message here...");
    m_inputField->setStyleSheet("QLineEdit {"
                               "padding: 12px;"
                               "border: 2px solid #dee2e6;"
                               "border-radius: 6px;"
                               "font-size: 14px;"
                               "}");
    connect(m_inputField, &QLineEdit::returnPressed, this, &ChatWindow::onSendClicked);

    m_sendButton = new QPushButton("Send");
    m_sendButton->setStyleSheet("QPushButton {"
                               "padding: 12px 20px;"
                               "background-color: #007bff;"
                               "color: white;"
                               "border: none;"
                               "border-radius: 6px;"
                               "font-weight: bold;"
                               "}"
                               "QPushButton:hover {"
                               "background-color: #0056b3;"
                               "}"
                               "QPushButton:disabled {"
                               "background-color: #6c757d;"
                               "}");
    connect(m_sendButton, &QPushButton::clicked, this, &ChatWindow::onSendClicked);

    m_clearButton = new QPushButton("Clear");
    m_clearButton->setStyleSheet("QPushButton {"
                                "padding: 12px 20px;"
                                "background-color: #6c757d;"
                                "color: white;"
                                "border: none;"
                                "border-radius: 6px;"
                                "}"
                                "QPushButton:hover {"
                                "background-color: #5a6268;"
                                "}");
    connect(m_clearButton, &QPushButton::clicked, this, &ChatWindow::onClearChat);

    m_inputLayout->addWidget(m_inputField, 4);
    m_inputLayout->addWidget(m_sendButton, 1);
    m_inputLayout->addWidget(m_clearButton, 1);
    m_mainLayout->addLayout(m_inputLayout);

    // 思考指示器
    m_thinkingLabel = new QLabel("AI is thinking...");
    m_thinkingLabel->setAlignment(Qt::AlignCenter);
    m_thinkingLabel->setStyleSheet("QLabel {"
                                  "color: #6c757d;"
                                  "font-style: italic;"
                                  "padding: 10px;"
                                  "}");
    m_thinkingLabel->hide();
    m_mainLayout->addWidget(m_thinkingLabel);

    setCentralWidget(m_centralWidget);
    setWindowTitle("DeepSeek AI Chat");
    resize(900, 700);

    // 创建菜单
    createMenu();

    statusBar()->showMessage("Ready to chat with DeepSeek AI");
}

void ChatWindow::createMenu()
{
    QMenu *fileMenu = menuBar()->addMenu("File");
    QAction *clearAction = fileMenu->addAction("Clear Chat");
    connect(clearAction, &QAction::triggered, this, &ChatWindow::onClearChat);

    QAction *exitAction = fileMenu->addAction("Exit");
    connect(exitAction, &QAction::triggered, this, &QWidget::close);

    QMenu *settingsMenu = menuBar()->addMenu("Settings");
    QAction *apiKeyAction = settingsMenu->addAction("API Key");
    connect(apiKeyAction, &QAction::triggered, this, &ChatWindow::setApiKey);

    QMenu *helpMenu = menuBar()->addMenu("Help");
    QAction *aboutAction = helpMenu->addAction("About");
    connect(aboutAction, &QAction::triggered, this, &ChatWindow::onAbout);
}

void ChatWindow::setApiKey()
{
    bool ok;
    QString newKey = QInputDialog::getText(this, "API Key",
                                        "Enter your DeepSeek API Key:",
                                        QLineEdit::Normal,
                                        m_apiKey,
                                        &ok);
    if (ok && !newKey.isEmpty()) {
        m_apiKey = newKey;
        statusBar()->showMessage("API Key updated", 3000);
        saveSettings();
    }
}



void ChatWindow::onSendClicked()
{
    QString message = m_inputField->text().trimmed();
    if (message.isEmpty()) return;

    addMessage(message, false);
    m_inputField->clear();

    showThinkingIndicator(true);
    callDeepSeekAPI(message);
}

void ChatWindow::callDeepSeekAPI(const QString &message)
{
    QUrl api_url("https://api.deepseek.com/v1/chat/completions");

    QNetworkRequest request(api_url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", ("Bearer " + m_apiKey).toUtf8());
    request.setRawHeader("Accept", "application/json");

    // 简化SSL配置
    QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
    sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
    request.setSslConfiguration(sslConfig);

    QJsonObject message_obj;
    message_obj["role"] = "user";
    message_obj["content"] = message;

    QJsonArray messages_array;
    messages_array.append(message_obj);

    QJsonObject request_body;
    request_body["model"] = "deepseek-chat";
    request_body["messages"] = messages_array;
    request_body["temperature"] = 0.7;
    request_body["max_tokens"] = 2000;
    request_body["stream"] = false;

    QJsonDocument doc(request_body);
    QByteArray data = doc.toJson();

    qDebug() << "Sending request to DeepSeek API...";
    m_networkManager->post(request, data);
    statusBar()->showMessage("Sending request to DeepSeek API...");
}

void ChatWindow::onApiReplyFinished(QNetworkReply *reply)
{
    showThinkingIndicator(false);

    if (reply->error() != QNetworkReply::NoError) {
        QString errorMsg = "Network Error: " + reply->errorString();
        addMessage(errorMsg, true);

        qDebug() << "Network error:" << reply->errorString();
        qDebug() << "HTTP status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        reply->deleteLater();
        return;
    }

    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    QByteArray response_data = reply->readAll();

    qDebug() << "HTTP Status:" << statusCode;
    qDebug() << "Response:" << QString(response_data);

    if (statusCode != 200) {
        addMessage("API returned HTTP error: " + QString::number(statusCode), true);
        reply->deleteLater();
        return;
    }

    QJsonDocument json_response = QJsonDocument::fromJson(response_data);

    if (json_response.isNull()) {
        addMessage("Failed to parse JSON response", true);
        qDebug() << "Raw response:" << QString(response_data);
        reply->deleteLater();
        return;
    }

    if (json_response.isObject()) {
        QJsonObject json_object = json_response.object();

        // 首先检查是否有错误
        if (json_object.contains("error")) {
            QJsonObject error_obj = json_object["error"].toObject();
            QString error_msg = error_obj.contains("message") ? error_obj["message"].toString() : "Unknown error";
            addMessage("API Error: " + error_msg, true);
        }
        // 检查choices数组
        else if (json_object.contains("choices")) {
            QJsonArray choices = json_object["choices"].toArray();
            if (!choices.isEmpty()) {
                QJsonObject choice = choices[0].toObject();

                if (choice.contains("message")) {
                    QJsonObject message_obj = choice["message"].toObject();
                    if (message_obj.contains("content")) {
                        QString content = message_obj["content"].toString();
                        addMessage(content, true);
                    } else {
                        addMessage("API response missing content field", true);
                    }
                }
                else if (choice.contains("text")) {
                    QString content = choice["text"].toString();
                    addMessage(content, true);
                }
                else if (choice.contains("content")) {
                    QString content = choice["content"].toString();
                    addMessage(content, true);
                }
                else {
                    addMessage("Unexpected choice format", true);
                }
            } else {
                addMessage("API returned empty choices array", true);
            }
        }
        else {
            addMessage("Unexpected API response format", true);
        }
    } else {
        addMessage("API response is not a JSON object", true);
    }

    reply->deleteLater();
}



void ChatWindow::onClearChat()
{
    QLayoutItem *child;
    while ((child = m_messagesLayout->takeAt(0)) != nullptr) {
        if (child->widget()) {
            delete child->widget();
        }
        delete child;
    }
}

void ChatWindow::onAbout()
{
    QMessageBox::about(this, "About",
        "DeepSeek AI Chat\n\n"
        "A simple chat application using DeepSeek API\n"
        "Built with Qt 5.14.2\n\n"
        "API Key: " + m_apiKey.left(10) + "...");
}

void ChatWindow::addMessage(const QString &message, bool isAI)
{
    ChatMessageWidget *messageWidget = new ChatMessageWidget(nullptr, message, isAI);
    m_messagesLayout->addWidget(messageWidget);

    QTimer::singleShot(100, this, [this]() {
        QScrollBar *scrollBar = m_scrollArea->verticalScrollBar();
        scrollBar->setValue(scrollBar->maximum());
    });
}

void ChatWindow::showThinkingIndicator(bool show)
{
    m_thinkingLabel->setVisible(show);
    m_sendButton->setEnabled(!show);
    m_inputField->setEnabled(!show);
    m_clearButton->setEnabled(!show);

    if (show) {
        statusBar()->showMessage("AI is thinking...");
    } else {
        statusBar()->showMessage("Ready");
    }
}

void ChatWindow::loadSettings()
{
    QSettings settings("DeepSeek", "ChatApp");
    m_apiKey = settings.value("apiKey", m_apiKey).toString();

    QRect geometry = settings.value("geometry", QRect(100, 100, 900, 700)).toRect();
    setGeometry(geometry);
}

void ChatWindow::saveSettings()
{
    QSettings settings("DeepSeek", "ChatApp");
    settings.setValue("apiKey", m_apiKey);
    settings.setValue("geometry", geometry());
}

